import {defineStore} from 'pinia';
import {Response} from "@/entity/response";
import {LoginUser, User} from "@/entity/user";
import API from "@/api/index";

export const user = defineStore('user', {
    state: () => ({
        token: useUtils().AuthUtils.getToken(),
        loginStatus: false,
        postGroup: "",
        roleGroup: "",
        userInfo: {} as User,
    }),
    getters: {},
    actions: {
        setAvatar(avatarUrl: string) {
            if (avatarUrl && avatarUrl != "") {
                this.userInfo.avatar = avatarUrl;
            }
        },
        login(loginForm: LoginUser) {
            const route = useRoute();
            useUtils().ModalUtils.loading("正在登陆中...");
            API.userApi.login(loginForm).then((res: any) => {
                const {code, data}: Response = res;
                const {AuthUtils, ModalUtils} = useUtils();
                if (code === 200) {
                    this.loginStatus = true;
                    this.token = data.token;
                    AuthUtils.setToken(data.token);
                    this.setUserInfo();
                    ModalUtils.msgSuccess("登录成功");
                    setTimeout(() => {
                        useUtils().ModalUtils.closeLoading();
                        console.log(route.query?.redirect)
                        if (route.query?.redirect) {
                            navigateTo(route.query.redirect.toString());
                        } else {
                            navigateTo("/");
                        }
                    }, 2500);
                } else {
                    useUtils().ModalUtils.closeLoading();
                }
            }).catch(() => {
                useUtils().ModalUtils.closeLoading();
            });
        },
        setUserInfo() {
            if (useUtils().AuthUtils.getToken() || this.token) {
                API.userApi.getUser().then((res: any) => {
                    const {code, data}: Response = res;
                    if (code === 200) {
                        this.loginStatus = true;
                        this.userInfo = data.user;
                        this.postGroup = data.postGroup;
                        this.roleGroup = data.roleGroup;
                    }
                });
            }
        },
        logout() {
            API.userApi.logout().then((res: any) => {
                const {code, msg}: Response = res;
                if (code === 200) {
                    this.clear();
                    useUtils().ModalUtils.msgSuccess(msg || "退出成功");
                }
            });
        },
        clear() {
            this.loginStatus = false;
            this.userInfo = {};
            this.token = "";
            this.postGroup = "";
            this.roleGroup = "";
            useUtils().AuthUtils.delToken();
        }
    },
    persist: true
})